﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FinanceTool.Entities;
using FinanceTool.Entities.Exceptions;

namespace FinanceTool.Components.Parsers
{
    internal class IngParser : IParser
    {
        public static IngParser Instance = new IngParser();

        private IngParser()
        {
        }

        public Transaction ParseToTransaction(string[] values)
        {
            Transaction transaction = null;

            if (values == null) return transaction;

            if (values.Length > 0)
            {
                transaction = new Transaction();
                transaction.Date = values[0] != null ? ConvertToDateTime(values[0]) : DateTime.MinValue;
                transaction.NameOrDescription = values[1];
                transaction.AcountNumber = values[2];
                transaction.AccountNumberAgainst = values[3];
                transaction.Code = values[4];
                transaction.IsCredit = ConvertToIsCredit(values[5]);
                transaction.Amount = ConvertToAmount(values[6], values[7]);
                transaction.MutationType = values[8];
                transaction.Announcements = values[9];
            }

            return transaction;
        }

        //31,99
        private decimal ConvertToAmount(string val1, string val2)
        {
            string strAmount = val1.Replace("\"", "") + "," + val2.Replace("\"", "");
            return decimal.Parse(strAmount);
        }

        private bool ConvertToIsCredit(string value)
        {
            if (string.IsNullOrEmpty(value)) throw new ParserException("Exception in IngParser: IsCredit is not valid.");

            if (value.ToUpper().Contains("AF")) return false;
            return true;
        }

        //20111031
        private DateTime ConvertToDateTime(string dateValue)
        {
            try
            {
                int year = Convert.ToInt32(dateValue.Substring(1, 4));
                int month = Convert.ToInt32(dateValue.Substring(5, 2));
                int day = Convert.ToInt32(dateValue.Substring(7, 2));

                return new DateTime(year, month, day);
            }
            catch(Exception ex)
            {
                var exception = new ParserException("Exception in IngParser.", ex);
                throw exception;
            }
        }
    }
}
